#!/usr/bin/python3
#-*- coding=utf-8 -*-

import os
import yaml
import argparse
from SqlManager import SqlManager

CONFIG_FILE = "import_player.yaml"

def get_config(file_name):
    """
    解析yaml
    :file_name: 配置文件名
    :returns: setting dict

    """

    if not os.path.exists(file_name):
        return {}

    with open(file_name, "r") as f:
        return yaml.load(f)


def main():
    config = get_config(os.path.join(os.path.dirname(__file__), CONFIG_FILE))
    setting = config.get('setting', {})
    db = setting.get('db', {})
    players = setting.get('players', {})
    file_info = setting.get('file', {})
    sql_mgr = SqlManager()
    sql_mgr.setConnect(db.get('database'), db.get('host'), db.get('user'), db.get('password'), db.get('character'), db.get('port'))
    sql_str = '''
    select table_name from information_schema.columns where table_schema = '{0}' and column_name = '{1}'
    '''.format(db.get('database'), db.get('column'))
    result = sql_mgr.queryTable(sql = sql_str)
    if not result:
        return

    with open(file_info.get('name'), 'wb') as f:
        f.write(file_info.get('head', '').encode(encoding='UTF-8', errors='strict') + '\n')
        for player in players:
            for table in result:
                f.write("{0}  {2}  roleID='{1}'\n".format(player.get('server'), player.get('roleID'), table[0]))
            f.write('\n\n')

if __name__ == "__main__":
    main()
